package com.vernhe.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

/**
 * 用于处理请求的Handler
 *
 * SimpleChannelInboundHandler：表示这个请求，拦截的是[入站]的请求
 */
public class CustomHandler extends SimpleChannelInboundHandler {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o)
            throws Exception {
        //得到channel，用于将缓冲区的消息发送
        Channel channel = channelHandlerContext.channel();
        //将受到的请求进行转型
        HttpObject msg = (HttpObject) o;

        //打印客户端的ip
        System.out.println(channel.remoteAddress());

        //定义发送的消息并存到缓冲区中
        ByteBuf content = Unpooled.copiedBuffer("Hello Netty~", CharsetUtil.UTF_8);

        //将返回的消息封装成Http请求
        FullHttpResponse response =
                new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                        HttpResponseStatus.OK,
                        content);

        //因为发送的是Http响应，因此需要设置响应头
        response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());

        //将响应发送回去
        channel.writeAndFlush(response);
    }
}
